package com.jeasonzhao.commons.inplacecache;

import java.util.LinkedHashMap;
import java.util.Iterator;
public class FIFOCache<K,V> extends AbstractCacheMap<K,V>
{

    public FIFOCache(int cacheSize)
    {
        this(cacheSize,0);
    }

    public FIFOCache(int cacheSize,long timeout)
    {
        super(cacheSize,timeout, new LinkedHashMap<K,CacheObject<K,V>>(cacheSize + 1,1.0f,false));
    }

    @Override
    public int prune()
    {
        int count = 0;
        CacheObject<K,V> first = null;
        Iterator<CacheObject<K,V>> values = this.getCacheMap()==null?
            null:this.getCacheMap().values().iterator();
        while(null!=values && values.hasNext())
        {
            CacheObject<K,V> co = values.next();
            if(co.isExpired() == true)
            {
                values.remove();
                count++;
            }
            if(first == null)
            {
                first = co;
            }
        }
        if(isFull())
        {
            if(first != null)
            {
                this.getCacheMap().remove(first.getKey());
                count++;
            }
        }
        return count;
    }
}
